package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func Access() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置跨域
		c.Header("Content-type", "application/json;charset=utf-8")
		c.Header("Access-Control-Allow-Origin", "*")  // 允许访问所有域
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")  // 支持跨域请求的方法,为了避免浏览次请求的多次'预检'请求
		c.Header("Access-Control-Allow-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Access-Control-Max-Age, Content-Type, itspire-token")  // header设置
		//c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")  // 允许跨域设置
		c.Header("Access-Control-Allow-Credentials", "true")  //  跨域请求是否允许带cookie信息，默认设置为true
		c.Set("content-type", "application/json;charset=utf-8")  // 设置返回格式是json
		if c.Request.Method == http.MethodOptions {
			c.Header("Access-Control-Max-Age", "172800")  // 预检缓存，单位为秒
			c.AbortWithStatus(http.StatusNoContent)
		}

		c.Next()
	}
}
